package com.gxuwz.endrskyweather.repository;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.gxuwz.endrskyweather.db.WeatherDBHelper;

public class FavoriteRepository {
    private WeatherDBHelper dbHelper;
    private Context context;
    //private Handler mainHandler;

    public FavoriteRepository(Context context) {
        this.context = context;
        this.dbHelper = new WeatherDBHelper(context);
        //this.mainHandler = new Handler(Looper.getMainLooper());
    }

    // 获取 DBHelper
    public WeatherDBHelper getDBHelper() {
        return dbHelper;
    }

    public int addFavoriteCity(String areaCode, String areaName) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            // 检查是否已收藏
            if (isCityFavorite(areaCode)) {
                //mainHandler.post(() -> Toast.makeText(context, "该地区已在收藏表中", Toast.LENGTH_SHORT).show());
                return 1;
            }
            // 插入新收藏
            String sql = "INSERT INTO " + WeatherDBHelper.TABLE_FAVORITE + " (" +
                    WeatherDBHelper.COLUMN_FAVORITE_AREA_CODE + ", " +
                    WeatherDBHelper.COLUMN_FAVORITE_AREA_NAME + ") VALUES (?, ?)";
            db.execSQL(sql, new Object[]{areaCode, areaName});
            //mainHandler.post(() -> Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show());
            return 0;
        } catch (Exception e) {
            //mainHandler.post(() -> Toast.makeText(context, "添加失败", Toast.LENGTH_SHORT).show());
            Log.e("addFavoriteCity", e.getMessage());
            return -1;
        }
    }

    // 判断是否已收藏
    public boolean isCityFavorite(String areaCode) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        try {
            String sql = "SELECT * FROM " + WeatherDBHelper.TABLE_FAVORITE + 
                         " WHERE " + WeatherDBHelper.COLUMN_FAVORITE_AREA_CODE + " = ?";
            cursor = db.rawQuery(sql, new String[]{areaCode});
            return cursor.getCount() > 0;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    // 获取所有收藏
    public Cursor getAllFavorites() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        try {
            //String sql = "SELECT * FROM " + WeatherDBHelper.TABLE_FAVORITE;
            cursor = db.query(WeatherDBHelper.TABLE_FAVORITE, null, null, null, null, null, null);
            Log.d("getAllFavorites", cursor.getCount() + " rows");
            return cursor;
        } catch (Exception e) {
            Log.d("getAllFavorites", cursor.getCount() + " rows");
            Log.d("getAllFavorites", e.getMessage());
            return null;
        }
    }

    // 删除收藏
    public boolean deleteFavoriteCity(String areaCode) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            // 删除收藏
            String sql = "DELETE FROM " + WeatherDBHelper.TABLE_FAVORITE +
                         " WHERE " + WeatherDBHelper.COLUMN_FAVORITE_AREA_CODE + " = ?";
            db.execSQL(sql, new Object[]{areaCode});
            //mainHandler.post(() -> Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show());
            return true;
        } catch (Exception e) {
            //mainHandler.post(() -> Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show());
            Log.e("deleteFavoriteCity", e.getMessage());
            return false;
        }
    }

    // 设置默认城市
    public boolean setDefaultCity(String areaCode) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            db.beginTransaction();
            // 先取消所有默认
            db.execSQL("UPDATE " + WeatherDBHelper.TABLE_FAVORITE + 
                      " SET " + WeatherDBHelper.COLUMN_FAVORITE_DEFAULT_FLAG + "=0");
            // 设置新的默认城市
            db.execSQL("UPDATE " + WeatherDBHelper.TABLE_FAVORITE + 
                      " SET " + WeatherDBHelper.COLUMN_FAVORITE_DEFAULT_FLAG + "=1" +
                      " WHERE " + WeatherDBHelper.COLUMN_FAVORITE_AREA_CODE + "=?", 
                      new Object[]{areaCode});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            Log.e("setDefaultCity", e.getMessage());
            return false;
        } finally {
            db.endTransaction();
        }
    }

    // 获取默认城市
    public String[] getDefaultCity() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.query(WeatherDBHelper.TABLE_FAVORITE,
                    new String[]{
                        WeatherDBHelper.COLUMN_FAVORITE_AREA_CODE,
                        WeatherDBHelper.COLUMN_FAVORITE_AREA_NAME
                    },
                    WeatherDBHelper.COLUMN_FAVORITE_DEFAULT_FLAG + "=1",
                    null, null, null, null);
            if (cursor.moveToFirst()) {
                return new String[]{
                    cursor.getString(0),
                    cursor.getString(1)
                };
            }
            return null;
        } finally {
            if (cursor != null) cursor.close();
        }
    }

}
